<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false">
      <van-cell v-for="(item, index) in list" :key="index">
        <comment-item :comment="item" @replay="$emit('replay', $event)"></comment-item>
      </van-cell>
    </van-list>
    <!-- 评论列表 -->

    <!-- 发布评论 -->
    <!-- <van-cell-group class="publish-wrap">
      <van-field clearable placeholder="请输入评论内容">
        <van-button slot="button" size="mini" type="info">发布</van-button>
      </van-field>
    </van-cell-group> -->
    <!-- /发布评论 -->
  </div>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'
import JSONBig from 'json-bigint'
export default {
  name: 'ArticleComment',
  components: { CommentItem },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'a',
      validator (value) {
        return ['a', 'c'].includes(value)
      }
    }
  },
  data () {
    return {
      // list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: null,
      totalCount: 0
    }
  },
  created () {
    this.onLoad()
  },
  methods: {
    async onLoad () {
      this.loading = true
      try {
        const { data: res } = await getComments({
          type: this.type, // 评论类型a对文章的评论，c对评论的回复
          source: JSONBig.stringify(this.source), // 源id，文章id或者评论id
          offset: this.offset, // 获取评论数据的偏移量，值为评论id表示从此id的数据向后端取数据
          limit: 10 // 每一页的评论是10条
        })
        // console.log(res)
        this.list.push(...res.data.results)
        this.totalCount = res.data.totalCount
        this.loading = false
        this.$emit('onLoad-success', res.data)
        if (res.data.results.length) {
          this.offset = res.data.last_id // 更新获取下一页数据的页码
        } else {
          this.finished = true // 没有数据了加载更多
        }
      } catch (err) {
        this.$toast.fail('获取评论失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}

.van-list {
  margin-bottom: 45px;
}
</style>
